package com.example.user.controller;

import com.example.shared.entity.EmailVerification;
import com.example.shared.entity.User;
import com.example.user.event.OnRegistrationCompleteEvent;
import com.example.user.payload.EmailRegistrationPayload;
import com.example.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Locale;

/**
 * Created by atom on 2017/11/20
 */
@RestController
public class RegistrationController {
    @Autowired
    private UserService userService;
    @Autowired
    private MessageSource messageSource;
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    private String appUrl = "";

    @GetMapping("/registration-confirm")
    public void registrationConfirm(HttpServletRequest req, @RequestParam("token") String token) throws Exception {
        Locale locale = req.getLocale();

        EmailVerification verification = userService.getVerificationFromToken(token);
        if (verification == null) {
            String message = messageSource.getMessage("auth.message.invalidToken", null, locale);
            throw new Exception(message);
        }

        User user = verification.getUser();
        Calendar cal = Calendar.getInstance();
        if (verification.getExpiryDate().getTime() - cal.getTime().getTime() <= 0) {
            String messageValue = messageSource.getMessage("auth.message.expired", null, locale);
            throw new Exception(messageValue);
        }
        user.setEnabled(true);
        userService.saveRegisteredUser(user);
    }

    @PostMapping("/register-with-email")
    public User register(HttpServletRequest req, @RequestBody @Validated EmailRegistrationPayload payload) {
        User u = userService.registerWithEmail(payload);
        eventPublisher.publishEvent(new OnRegistrationCompleteEvent(u, req.getLocale(), appUrl));
        return u;
    }
}
